package com.recipedb.sprint.controller;

import com.recipedb.sprint.service.PointsRewardsService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import com.recipedb.sprint.security.JwtUtil;
@RestController
@RequestMapping("/api/points")
public class PointsRewardsController {

    private final PointsRewardsService pointsRewardsService;

    public PointsRewardsController(PointsRewardsService pointsRewardsService) {
        this.pointsRewardsService = pointsRewardsService;
    }

    /**
     * 查询积分余额
     */
    @GetMapping("/balance")
    public ResponseEntity<Map<String, Object>> getPointsBalance(@RequestHeader("Authorization") String token) {
        try {
            // 截取 Bearer 前缀
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 解析 Token 获取 userid
            String username = JwtUtil.validateToken(pureToken);
            if (username == null) {
                throw new RuntimeException("Token无效或已过期");
            }
            // 假设通过 username 查询 userid（需确保 Service 层支持）
            Long userid = pointsRewardsService.getUserIdByUsername(username);

            Map<String, Object> data = pointsRewardsService.getPointsBalance(userid);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 查询积分明细
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getPointsHistory(@RequestHeader("Authorization") String token) {
        try {
            // 1. 处理 Token 前缀
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 2. 解析 Token 获取 username
            String username = JwtUtil.validateToken(pureToken);
            if (username == null) {
                throw new RuntimeException("Token无效或已过期");
            }
            // 3. 通过 username 查询 userid（调用实现的方法）
            Long userid = pointsRewardsService.getUserIdByUsername(username);

            // 4. 查询积分明细
            var data = pointsRewardsService.getPointsHistory(userid);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 每日登录积分奖励（在用户登录成功后调用）
     */
    @PostMapping("/daily-login")
    public ResponseEntity<Map<String, Object>> awardDailyLoginPoints(@RequestHeader("Authorization") String token) {
        try {
            // 1. 处理 Token 前缀
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 2. 解析 Token 获取 username
            String username = JwtUtil.validateToken(pureToken);
            if (username == null) {
                throw new RuntimeException("Token无效或已过期");
            }
            // 3. 通过 username 查询 userid
            Long userid = pointsRewardsService.getUserIdByUsername(username);

            // 4. 发放每日登录积分
            pointsRewardsService.awardDailyLoginPoints(userid);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "每日登录积分已发放");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}